package com.ruoyi.miniapp.ali;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.miniapp.domain.ResItem;
import com.ruoyi.miniapp.domain.ResType;

/**
 * @author lobyliang on 2022-1-13 18:42
 */
public class OSSKeyUtil
{
    public static String getFullPath(String fullPath,Long userId, String username){
        if(ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(username)){
            String str = username + userId;
            return fullPath.replace("%USER%", str);
        }
        return fullPath;
    }

    public static String getOSSKey(ResItem resItem, ResType resType, Long userId, String userUnionId){
        if(resItem != null && resType!=null){
            String fullPath = resType.getFullPath();
            String fileFullPath = resItem.getFileFullPath();
            fullPath = getFullPath(fullPath,userId,userUnionId);
            int idx = fileFullPath.indexOf(fullPath);
            if(idx>=0)
            {
                return fileFullPath.substring(idx);
            }
            String fileName = resItem.getOriginFileName();
            if(ObjectUtils.isEmpty(fullPath) || ObjectUtils.isEmpty(fileName)){
                return null;
            }
            if(! fullPath.endsWith("/")){
                fullPath = "/" + fullPath;
            }
            return fullPath + fileName;
        }
        return null;
    }

    public static String combineOSSKey(String fullPath, String fileName){
        if(! fullPath.endsWith("/")){
            fullPath = "/" + fullPath;
        }
        return fullPath + fileName;
    }

    public static String getFullPath(String remoteBaseUrl, String fullPath, String fileName){
        if(! fullPath.endsWith("/")){
            fullPath = "/" + fullPath;
        }
        if(! remoteBaseUrl.endsWith("/") && ! fileName.startsWith("/")){
            return remoteBaseUrl + "/" + fullPath + fileName;
        }
        return remoteBaseUrl + fullPath + fileName;
    }
}
